package zunge.twitterdel.bean;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

public class DelTweetDAO {
	private BeanFactory<DelTweet> factory;
	private BeanTable<DelTweet> tweetTable;
	
	static String jdbcDriver = "com.mysql.jdbc.Driver";
	
	public DelTweetDAO(String jdbcURL, String userName, String password) throws DAOException {
		try{
			
	        tweetTable = BeanTable.getSQLInstance(DelTweet.class,"deltweet",
	        									jdbcDriver, jdbcURL, userName, password);
	        
	        if (!tweetTable.exists()) tweetTable.create("id");
	        tweetTable.setIdleConnectionCleanup(true);
	        factory = tweetTable.getFactory();
	        
		}catch (BeanFactoryException e) {throw new DAOException(e);}
	}
	
	public void create(DelTweet delTweet) throws DAOException{
		try{
			
			Transaction.begin();
			DelTweet delTweetDB = factory.create();
			factory.copyInto(delTweet, delTweetDB);
			Transaction.commit();
			
		}catch(RollbackException e){throw new DAOException(e);
		}finally{
			if(Transaction.isActive()){
				Transaction.rollback();
			}
		}
	}
	
}
